﻿$.fn.InitSelect2 = function (title, url, name, callback, multiple, length,rst) {
    $(this).select2({
        placeholder: title,
        allowClear: true,
        minimumInputLength: length || 1,
        multiple: multiple || false,
        ajax: {
            type: "post",
            url: url,
            dataType: 'json',
            quietMillis: 500,
            data: function (term, page) {
                return {
                    keyword: term,
                    page_limit: 10,
                    apikey: "NoUse"
                };
            },
            results: function (data, page) {
                return {
                    results: data
                };
            }
        },
        initSelection: function (element, callback) {
            var id = element.val();
            var val = element.attr("sn");
            var data;
            if (id.indexOf(",") > 0) {
                var datas = [];
                var names = val.split(",");
                $.each(id.split(","), function (key, val) {
                    datas.push({ id: val, name: names[key], code: names[key], invoiceNo: names[key], fullNameCn: val, genericName: val });
                });
                data = datas;
            } else {
                data = { id: id, name: val, code: val, invoiceNo: val, fullNameCn: val, genericName: val };
            }
            callback(data);
        },
        formatResult: function (dt) {
            var result = "";
            if (name.split(",").length > 1) {
                var names = name.split(",");
                for (var i = 0; i < names.length; i++) {
                    if (i == 0) {
                        result += dt[names[i]];
                    }
                    else {
                        if (dt[names[i]]) {
                            result += "[" + dt[names[i]] + "]";
                        }
                    }
                }
            }
            else {
                result = dt[name];
                rst = dt["rst"];
            }
            return result;
        },
        formatSelection: function (dt, container) {
            var result;
            if (callback) {
                callback(dt.id,rst);
            }
            if (name.split(",").length > 1) {
                result = dt[name.split(",")[0]];
            }
            else {
                result = dt[name];
            }
            return result;
        }
    });
}